package cn.hm.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * @author Mxb
 * @version 1.0
 * @date 2020/7/16 14:32
 */
@Configuration
//@EnableGlobalMethodSecurity(securedEnabled = true)  //使用注解授权
@EnableGlobalMethodSecurity(prePostEnabled = true)  //使用注解授权
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    //定义用户信息服务（查询用户信息）使用内存的方式
    //@Bean
    //public UserDetailsService userDetailsService() {
    //    InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager();
    //    manager.createUser(User.withUsername("zhang3").password("123").authorities("p1").build());
    //    manager.createUser(User.withUsername("li4").password("123").authorities("p2").build());
    //    return manager;
    //}

    //密码编码器(定义密码比对方式) 不加密 字符串形式
    @Bean
    public PasswordEncoder passwordEncoder() {
        return NoOpPasswordEncoder.getInstance();
    }

    //@Autowired
    //private LogoutSuccessHandler logoutSuccessHandler;
    //
    //@Autowired
    //private LogoutHandler logoutHandler;

    //拦截用户请求（安全拦截机制）
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers().permitAll()  //放行其他请求
                // 授权
                .antMatchers("/r/r1").hasAuthority("p1")
                .antMatchers("/r/r2").hasAuthority("p2")
                .antMatchers("/r/**").authenticated() //所有/r/**请求要认证通过
                .anyRequest().permitAll()

                // 登录 配置
                .and()
                .formLogin()    // 允许表单登录 自定义页面使用
                //.loginPage("/login-view")   //指定登录页面
                .loginProcessingUrl("/login")  //配置登录页面请求地址
                .successForwardUrl("/login-success")  //自定义登录成功的页面地址
                .permitAll()

                // 注销登录
                .and()
                .logout()
                .logoutUrl("/logout")
                .logoutSuccessUrl("/?logout")
                //.logoutSuccessHandler(logoutSuccessHandler)
                //.addLogoutHandler(logoutHandler)
                .invalidateHttpSession(true);  //指定是否在退出时让HttpSession无效，默认为true

        // 会话控制
        http.sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED)
                //.expiredUrl("/?error=EXPIRED_SESSION")
                .invalidSessionUrl("/?error=INVALID_SESSION");
    }
}
